<template>
	<view class="avatar-list-page">
		<!-- 自定义导航栏 -->
		<view class="custom-header">
			<!-- 状态栏占位 -->
			<view class="status-bar"></view>

			<!-- 导航栏 -->
			<view class="nav-bar" :style=" {top: getStatusBarHeight() + 'px'}">
				<!-- 左侧返回按钮 -->
				<view class="nav-left" @click="goBack">
					<uni-icons type="left" size="24" color="#fff"></uni-icons>
				</view>
			</view>

			<!-- 标题区域 -->
			<view class="header-content">
				<view class="title">头像精选</view>
				<view class="subtitle">{{ getCurrentDate() }}推荐</view>
				<view class="description">精选优质头像，让你的社交更有魅力</view>
			</view>
		</view>

		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 统计信息 -->
			<view class="stats-info">
				<text>共{{ total }}张, {{ viewCount }}人看过</text>
			</view>

			<!-- 头像网格 -->
			<view class="avatar-grid">
				<view class="avatar-item" v-for="(item, index) in avatrData" :key="item.id">
					<image :src="item.avatar" class="avatar-img" mode="aspectFill" @load="handleImageStatus(index)"
						@error="handleImageStatus(index, false)" />
					<!-- 加载状态 -->
					<view class="loading-overlay" v-if="!item.loaded">
						<uni-icons type="spinner-cycle" size="24" color="#999"></uni-icons>
					</view>

					<!-- 操作按钮 -->
					<view class="action-overlay">
						<view class="action-btn preview-btn" @click="previewAvatar(item)">
							<uni-icons type="eye" size="16" color="#fff"></uni-icons>
						</view>
						<view class="action-btn download-btn" @click="downloadAvatar(item.avatar)">
							<uni-icons type="download" size="16" color="#fff"></uni-icons>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore">
				<view class="load-btn" @click="loadMore">
					<uni-icons type="reload" size="20" color="#666"></uni-icons>
					<text>加载更多</text>
				</view>
			</view>

			<!-- 没有更多数据 -->
			<view class="no-more" v-if="!hasMore && avatrData.length > 0">
				<text>没有更多了</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		apiAvatar
	} from "@/api/apis.js"
	import {
		getStatusBarHeight
	} from "@/utils/system.js"
	import {
		ref,
		onMounted,
		onUnmounted
	} from "vue"

	// 响应式数据
	const avatrData = ref([])
	const total = ref(0)
	const viewCount = ref(0)
	const pageNum = ref(1)
	const pageSize = ref(20)
	const hasMore = ref(true)
	const loading = ref(false)

	// 获取头像数据
	const loadAvatar = async (isLoadMore = false) => {
		if (loading.value) return

		loading.value = true
		try {
			const res = await apiAvatar({
				pageNum: pageNum.value,
				pageSize: pageSize.value
			})

			if (res.data?.list) {
				const newList = res.data.list.map(item => ({
					...item,
					loaded: false
				}))

				avatrData.value = isLoadMore ? [...avatrData.value, ...newList] : newList
				total.value = res.data.total || 0
				viewCount.value = Math.floor(Math.random() * 500) + 100
				hasMore.value = avatrData.value.length < total.value
			}
		} catch (error) {
			console.error('加载头像失败:', error)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	// 加载更多
	const loadMore = () => {
		if (hasMore.value && !loading.value) {
			pageNum.value++
			loadAvatar(true)
		}
	}

	// 图片加载状态处理
	const handleImageStatus = (index, loaded = true) => {
		if (avatrData.value[index]) {
			avatrData.value[index].loaded = loaded
		}
	}

	// 预览头像
	const previewAvatar = (item) => {
		if (!item || !item.avatar) {
			uni.showToast({
				title: '图片地址无效',
				icon: 'none'
			})
			return
		}

		uni.previewImage({
			urls: [item.avatar],
			current: item.avatar,
			indicator: 'number',
			success: () => {
				console.log('预览成功')
				// 预览成功后显示下载选项
				setTimeout(() => {
					showDownloadOptions(item)
				}, 500)
			},
			fail: (err) => {
				console.error('预览失败:', err)
				uni.showToast({
					title: '预览失败',
					icon: 'none'
				})
			}
		})
	}

	// 显示下载选项
	const showDownloadOptions = (item) => {
		uni.showActionSheet({
			itemList: ['保存到相册', '分享给好友'], // 移除了未实现的"设为头像"选项
			success: (res) => {
				switch (res.tapIndex) {
					case 0:
						downloadAvatar(item.avatar)
						break
					case 1:
						shareAvatar(item)
						break
				}
			}
		})
	}

	// 下载头像到相册
	const downloadAvatar = (imageUrl) => {
		// #ifdef H5
		// H5平台下载处理
		uni.showLoading({
			title: '下载中...'
		})

		// 创建下载链接
		const link = document.createElement('a')
		link.href = imageUrl
		link.download = `avatar_${Date.now()}.jpg`
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link)

		uni.hideLoading()
		uni.showToast({
			title: '下载成功',
			icon: 'success'
		})
		// #endif

		// #ifdef MP-WEIXIN
		// 微信小程序下载处理
		uni.showLoading({
			title: '下载中...'
		})

		// 下载图片
		uni.downloadFile({
			url: imageUrl,
			success: (res) => {
				if (res.statusCode === 200) {
					// 使用 getImageInfo 获取图片信息并重命名文件
					uni.getImageInfo({
						src: res.tempFilePath,
						success: async (info) => {
							// 1. 把 .bin 临时路径复制一份带 .jpg 后缀的临时文件
							const fs = uni.getFileSystemManager();
							const newPath =
								`${wx.env.USER_DATA_PATH}/downloaded_${Date.now()}.jpg`;
							fs.copyFileSync(info.path, newPath);

							// 2. 保存到相册
							uni.saveImageToPhotosAlbum({
								filePath: newPath,
								success: () => {
									uni.showToast({
										title: '保存成功',
										icon: 'none'
									});
								},
								fail: (err) => {
									if (err.errMsg.includes('cancel')) {
										uni.showToast({
											title: '已取消',
											icon: 'none'
										});
									} else if (err.errMsg.includes('auth')) {
										uni.showModal({
											title: '提示',
											content: '需要授权保存到相册',
											success: (res) => {
												res.confirm && uni
													.openSetting();
											}
										});
									} else {
										uni.showToast({
											title: '保存失败：' + err.errMsg,
											icon: 'none'
										});
									}
								},
								complete: () => uni.hideLoading()
							});
						},
						fail: () => {
							uni.showToast({
								title: '获取图片信息失败',
								icon: 'none'
							});
							uni.hideLoading();
						}
					});
				}
			},
			fail: () => {
				uni.hideLoading()
				uni.showToast({
					title: '下载失败',
					icon: 'none'
				})
			}
		})
		// #endif

		// #ifdef APP
		// APP端下载处理
		uni.showLoading({
			title: '下载中...'
		})

		// 下载图片
		uni.downloadFile({
			url: imageUrl,
			success: (res) => {
				if (res.statusCode === 200) {
					// 保存到相册
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							uni.hideLoading()
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
						},
						fail: (err) => {
							uni.hideLoading()
							if (err.errMsg.includes('auth')) {
								uni.showModal({
									title: '提示',
									content: '需要授权保存到相册',
									success: (res) => {
										res.confirm && uni.openSetting();
									}
								});
							} else {
								uni.showToast({
									title: '保存失败',
									icon: 'none'
								});
							}
						}
					});
				}
			},
			fail: () => {
				uni.hideLoading()
				uni.showToast({
					title: '下载失败',
					icon: 'none'
				})
			}
		})
		// #endif
	}

	// 分享头像
	const shareAvatar = (item) => {
		// #ifdef H5
		uni.showToast({
			title: 'H5暂不支持分享功能',
			icon: 'none'
		})
		// #endif

		// #ifdef MP-WEIXIN
		// 在微信小程序中，分享功能需要通过右上角菜单或按钮触发
		uni.showModal({
			title: '分享提示',
			content: '请点击右上角"..."按钮，选择"分享给朋友"或"分享到朋友圈"',
			showCancel: false,
			confirmText: '知道了'
		})
		// #endif

		// #ifdef APP
		// APP端分享功能
		uni.showModal({
			title: '分享提示',
			content: 'APP端分享功能开发中，敬请期待',
			showCancel: false,
			confirmText: '知道了'
		})
		// #endif
	}

	// 返回上一页
	const goBack = () => uni.navigateBack()

	// 获取当前日期
	const getCurrentDate = () => {
		const now = new Date()
		return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
	}

	// 生命周期
	onMounted(() => loadAvatar())

	// 页面销毁时清理资源
	onUnmounted(() => {
		// 清空数据
		avatrData.value = []
		total.value = 0
		viewCount.value = 0
		pageNum.value = 1
		hasMore.value = true
		loading.value = false

		console.log('头像列表页面已销毁，资源已清理')
	})

	// 微信小程序分享配置
	// #ifdef MP-WEIXIN
	// 定义分享给朋友
	defineExpose({
		onShareAppMessage() {
			return {
				title: '精选头像分享',
				imageUrl: avatrData.value[0]?.avatar || '',
				path: '/pagesMember/avatarList/avatarList'
			}
		},
		// 定义分享到朋友圈
		onShareTimeline() {
			return {
				title: '精选头像分享',
				imageUrl: avatrData.value[0]?.avatar || '',
				query: ''
			}
		}
	})
	// #endif
</script>

<style lang="scss" scoped>
	.avatar-list-page {
		min-height: 100vh;
		background: #0a0e29;
		/* 深蓝色背景 */
		position: relative;
		overflow: hidden;
		/* 隐藏超出容器的星星 */
	}

	/* 星空效果 */
	.avatar-list-page::before {
		content: "";
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-image:
			radial-gradient(2px 2px at 20px 30px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(2px 2px at 40px 70px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(2px 2px at 50px 160px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(2px 2px at 90px 40px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(2px 2px at 130px 80px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(3px 3px at 230px 140px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(2px 2px at 260px 180px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(3px 3px at 400px 90px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(2px 2px at 530px 150px, #fff, rgba(0, 0, 0, 0)),
			radial-gradient(3px 3px at 600px 100px, #fff, rgba(0, 0, 0, 0));
		background-repeat: repeat;
		animation: twinkle 10s infinite;
	}

	/* 星云效果 */
	.avatar-list-page::after {
		content: "";
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
		animation: nebula 20s infinite alternate;
	}

	/* 星星闪烁动画 */
	@keyframes twinkle {
		0% {
			opacity: 0.5;
		}

		50% {
			opacity: 1;
		}

		100% {
			opacity: 0.5;
		}
	}

	/* 星云流动动画 */
	@keyframes nebula {
		0% {
			transform: scale(1);
			opacity: 0.1;
		}

		100% {
			transform: scale(1.1);
			opacity: 0.2;
		}
	}

	/* 自定义导航栏 */
	.custom-header {
		position: relative;
		z-index: 100;

		.status-bar {
			height: 44rpx;
			background: transparent;
		}

		.nav-bar {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 30rpx;

			.nav-left {
				width: 80rpx;
				height: 80rpx;
				background: rgba(255, 255, 255, 0.2);
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				backdrop-filter: blur(10rpx);
				transition: all 0.3s ease;

				&:active {
					transform: scale(0.95);
					background: rgba(255, 255, 255, 0.3);
				}
			}

			.nav-right {
				display: flex;
				gap: 20rpx;

				.action-btn {
					width: 60rpx;
					height: 60rpx;
					background: rgba(255, 255, 255, 0.2);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					backdrop-filter: blur(10rpx);
					transition: all 0.3s ease;

					&:active {
						transform: scale(0.95);
						background: rgba(255, 255, 255, 0.3);
					}
				}
			}
		}

		.header-content {
			padding: 40rpx 30rpx 60rpx;
			text-align: center;

			.title {
				font-size: 48rpx;
				font-weight: 700;
				color: #fff;
				margin-bottom: 20rpx;
				text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.3);
			}

			.subtitle {
				font-size: 28rpx;
				color: rgba(255, 255, 255, 0.9);
				margin-bottom: 16rpx;
				font-weight: 500;
			}

			.description {
				font-size: 26rpx;
				color: rgba(255, 255, 255, 0.8);
				line-height: 1.5;
				max-width: 500rpx;
				margin: 0 auto;
			}
		}
	}

	/* 主要内容区域 */
	.main-content {
		background: #fff;
		border-radius: 40rpx 40rpx 0 0;
		min-height: calc(100vh - 400rpx);
		position: relative;
		z-index: 10;
		padding: 40rpx 30rpx;
		box-shadow: 0 -20rpx 60rpx rgba(0, 0, 0, 0.1);

		.stats-info {
			text-align: center;
			padding: 20rpx 0 40rpx;
			border-bottom: 1rpx solid #f0f0f0;
			margin-bottom: 40rpx;

			text {
				font-size: 28rpx;
				color: #666;
				font-weight: 500;
			}
		}

		.avatar-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;
			margin-bottom: 40rpx;

			.avatar-item {
				aspect-ratio: 1;
				border-radius: 20rpx;
				overflow: hidden;
				box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
				position: relative;
				transition: all 0.3s ease;
				cursor: pointer;

				&:hover {
					transform: translateY(-8rpx);
					box-shadow: 0 16rpx 40rpx rgba(0, 0, 0, 0.15);
				}

				&:active {
					transform: scale(0.98);
				}

				.avatar-img {
					width: 100%;
					height: 100%;
					object-fit: cover;
					transition: all 0.3s ease;
				}

				.loading-overlay {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background: rgba(255, 255, 255, 0.9);
					display: flex;
					align-items: center;
					justify-content: center;
					backdrop-filter: blur(4rpx);
				}

				/* 操作按钮覆盖层 */
				.action-overlay {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background: rgba(0, 0, 0, 0.3);
					display: flex;
					align-items: center;
					justify-content: center;
					gap: 20rpx;
					opacity: 0;
					transition: all 0.3s ease;
					backdrop-filter: blur(4rpx);
				}

				.action-btn {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					transition: all 0.3s ease;
					cursor: pointer;
					border: 2rpx solid rgba(255, 255, 255, 0.3);

					&:active {
						transform: scale(0.9);
					}

					/* 移动端按钮更大更明显 */
					@media (max-width: 750rpx) {
						width: 70rpx;
						height: 70rpx;
						border-width: 3rpx;
					}
				}

				.preview-btn {
					background: rgba(64, 158, 255, 0.8);

					&:hover {
						background: rgba(64, 158, 255, 1);
					}
				}

				.download-btn {
					background: rgba(103, 194, 58, 0.8);

					&:hover {
						background: rgba(103, 194, 58, 1);
					}
				}

				/* 悬停时显示操作按钮 */
				&:hover .action-overlay {
					opacity: 1;
				}

				/* 触摸设备上，点击时也显示操作按钮 */
				&:active .action-overlay {
					opacity: 1;
				}

				/* 在移动端，始终显示操作按钮 */
				@media (max-width: 750rpx) {
					.action-overlay {
						opacity: 1;
						background: rgba(0, 0, 0, 0.5);
					}
				}
			}
		}

		.load-more {
			text-align: center;
			padding: 40rpx 0;

			.load-btn {
				display: inline-flex;
				align-items: center;
				gap: 12rpx;
				padding: 20rpx 40rpx;
				background: #f8f9fa;
				border-radius: 30rpx;
				border: 1rpx solid #e9ecef;
				transition: all 0.3s ease;

				&:active {
					background: #e9ecef;
					transform: scale(0.98);
				}

				text {
					font-size: 28rpx;
					color: #666;
					font-weight: 500;
				}
			}
		}

		.no-more {
			text-align: center;
			padding: 40rpx 0;

			text {
				font-size: 26rpx;
				color: #999;
			}
		}
	}

	/* 响应式优化 */
	@media (max-width: 750rpx) {
		.avatar-grid {
			gap: 16rpx;
		}

		.main-content {
			padding: 30rpx 20rpx;
		}

		.custom-header .header-content {
			padding: 30rpx 20rpx 50rpx;
		}
	}
</style>